﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ThreeByte.ActiveDeck.Config;
using System.Collections.ObjectModel;
using System.Xml.Linq;
using ThreeByte.Media;

namespace ThreeByte.ActiveDeck.Content
{
    /// <summary>
    /// Interaction logic for CategoriesPreview.xaml
    /// </summary>
    public partial class MultipleChoicePreview : UserControl, IPreviewControl
    {

        public PageConfig Config { get; set; }

        public MultipleChoicePreview(MultipleChoiceConfig config) {
            InitializeComponent();
            Config = config;
            DataContext = config;
            config.Refresh();
            config.Answers.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Answers_CollectionChanged);
            RefreshAnswers(config.Answers);
        }

        void Answers_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) {
          RefreshAnswers((ObservableCollection<Answer>)sender);
            
        }

        private void RefreshAnswers(ObservableCollection<Answer> answers) {
            AnswerGrid.Children.Clear();
            AnswerGrid.RowDefinitions.Clear();

            int row = 0;
            foreach (Answer a in answers) {
                AnswerGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star), MaxHeight = 100 });

                //Insert the background
                Image newImage = new Image();
                newImage.SetValue(Grid.RowProperty, row);
                AnswerGrid.Children.Add(newImage);

                TextBlock newTextBlock = new TextBlock();
                Binding newBinding = new Binding("Text") { Source = a };
                newTextBlock.SetBinding(TextBlock.TextProperty, newBinding);
                newTextBlock.SetValue(Grid.RowProperty, row);
                //newTextBlock.SetValue(Grid.ColumnProperty, 1);
                AnswerGrid.Children.Add(newTextBlock);

                Button newButton = new Button();
                newButton.SetValue(Grid.RowProperty, row);
                AnswerGrid.Children.Add(newButton);
                row++;
            }

        }

        //Happens on Dispatcher Thread
        public PresentationPageConfiguration GetPageConfiguration() {
            XNamespace ns = Service.ServiceConfiguration.NAMESPACE;

            PresentationPageConfiguration newPage = new PresentationPageConfiguration();

            MultipleChoiceConfig config = (MultipleChoiceConfig)DataContext;
            XElement pageNode = config.GetPresentationXml("MultipleChoiceQuestion");
            
            if(config.OneTime) {
                pageNode.Add(new XAttribute("OneTime", config.OneTime));
            }

            pageNode.Add(config.GetGradingConfig());

            //Disable the Interactive Elements
            LayerRenderer.Hide();
            //Snap the Background
            this.UpdateLayout();
            Size exportSize = ((config.LayoutOrientation == Orientation.LandscapeLeft) || (config.LayoutOrientation == Orientation.LandscapeRight) ?
                                    ImageUtil.DefaultLanscapeSize : ImageUtil.DefaultPortraitSize);
            GraphicResource backgroundResource = new GraphicResource(ImageUtil.SaveToBitmapSource(LayoutRoot, exportSize), null, ImageType.JPEG);
            newPage.Resources[backgroundResource.ID] = backgroundResource;
            XElement backgroundNode = new XElement(ns + "BackgroundImage", new XAttribute("ResourceID", backgroundResource.ID));
            pageNode.Add(backgroundNode);

            //Enable the Interactive Elements
            LayerRenderer.Show();
            this.UpdateLayout();

            //Locate the Toggle Buttons
            int value = 0;
            XElement imageToggleOnElement = null;
            XElement imageToggleOffElement = null;

            foreach (UIElement el in AnswerGrid.Children) {
                Button b = el as Button;
                if (b == null) {
                    continue;
                }

                value++;
                XElement toggleButtonElement = new XElement(ns + "Button");
                toggleButtonElement.Add(new XElement(ns + "Action", new XAttribute("Type", "Toggle"), new XAttribute("Value", value)));

                Point bPos = b.TransformToAncestor(LayoutRoot).Transform(new Point(0, 0));
                toggleButtonElement.Add(new XAttribute("Top", (int)(bPos.Y)));
                toggleButtonElement.Add(new XAttribute("Left", (int)(bPos.X)));
                toggleButtonElement.Add(new XAttribute("Width", (int)(b.ActualWidth)));
                toggleButtonElement.Add(new XAttribute("Height", (int)(b.ActualHeight)));
                
                //Add OnImage
                if (imageToggleOnElement != null) {
                    XElement newToggleOnElement = new XElement(imageToggleOnElement);
                    toggleButtonElement.Add(newToggleOnElement);
                } else {
                    //Snap it
                    LayerRenderer.SetActive();
                    GraphicResource toggleResource = new GraphicResource(ImageUtil.SaveToBitmapSource(b));
                    newPage.Resources[toggleResource.ID] = toggleResource;
                    imageToggleOnElement = new XElement(ns + "ImageOn", new XAttribute("ResourceID", toggleResource.ID));
                    toggleButtonElement.Add(imageToggleOnElement);
                    this.UpdateLayout();
                }

                //Add OffImage
                if (imageToggleOffElement != null) {
                    XElement newToggleOffElement = new XElement(imageToggleOffElement);
                    toggleButtonElement.Add(newToggleOffElement);
                } else {
                    //Snap it - Update the look
                    LayerRenderer.SetInactive();
                    GraphicResource toggleResource = new GraphicResource(ImageUtil.SaveToBitmapSource(b));
                    newPage.Resources[toggleResource.ID] = toggleResource;
                    imageToggleOffElement = new XElement(ns + "ImageOff", new XAttribute("ResourceID", toggleResource.ID));
                    toggleButtonElement.Add(imageToggleOffElement);
                    LayerRenderer.SetActive();
                    this.UpdateLayout();
                }

                pageNode.Add(toggleButtonElement);
            }

            //Locate the ActionButton
            XElement buttonElement = new XElement(ns + "Button");
            buttonElement.Add(ActionButton.Action.ToXml());

            Point buttonPos = ActionButton.TransformToAncestor(LayoutRoot).Transform(new Point(0, 0));
            buttonElement.Add(new XAttribute("Top", (int)(buttonPos.Y)));
            buttonElement.Add(new XAttribute("Left", (int)(buttonPos.X)));
            buttonElement.Add(new XAttribute("Width", (int)(ActionButton.ActualWidth)));
            buttonElement.Add(new XAttribute("Height", (int)(ActionButton.ActualHeight)));
            

            //Snap the Button
            LayerRenderer.SetActive();
            GraphicResource buttonOnResource = new GraphicResource(ImageUtil.SaveToBitmapSource(ActionButton));
            newPage.Resources[buttonOnResource.ID] = buttonOnResource;
            XElement imageOnNode = new XElement(ns + "ImageOn", new XAttribute("ResourceID", buttonOnResource.ID));
            buttonElement.Add(imageOnNode);
            this.UpdateLayout();

            //Snap the Off Button
            LayerRenderer.SetInactive();
            GraphicResource buttonOffResource = new GraphicResource(ImageUtil.SaveToBitmapSource(ActionButton));
            newPage.Resources[buttonOffResource.ID] = buttonOffResource;
            XElement imageOffNode = new XElement(ns + "ImageOff", new XAttribute("ResourceID", buttonOffResource.ID));
            buttonElement.Add(imageOffNode);
            pageNode.Add(buttonElement);

            newPage.ConfigXml = pageNode;
            return newPage;
        }

    }
}
